package com.gemme.gemme.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.gemme.gemme.R;
import com.gemme.gemme.SearchActivity;
import com.gemme.gemme.fragment.BaseLazyFragment;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.view.HomeHeadView;
import com.gemme.gemme.view.NoDataView;
import com.gemme.gemme.view.StaggeredDividerItemDecoration;
import com.gemme.gemme.wode.ActionActivity;
import com.gemme.gemme.wode.ProductNewActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by sp on 2019/7/18.
 * 首页
 */
public class Home2Fragment extends BaseLazyFragment implements View.OnClickListener {

    View inflate;
    public Context mContext;
    private int pageIndex = 1;
    private int pageSize = 10;
    private List<PageAllProductBean.DataBean.RecordsBean> recordDatas = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        inflate = inflater.inflate(R.layout.fragment_home2_new, container, false);

        mContext = Home2Fragment.this.getContext();
        initView(inflate);
        initData();

        return inflate;
    }

    private SmartRefreshLayout mSmartRefreshLayout;
    private SwipeRecyclerView mRecyclerView;
    HomeHeadView defineHeadView;
    LinearLayout ll_content;
    ViewGroup root_view;

    private void initView(View inflate) {

        mSmartRefreshLayout = inflate.findViewById(R.id.mSmartRefreshLayout);
        mRecyclerView = inflate.findViewById(R.id.recycler_view);
        defineHeadView = new HomeHeadView(mContext);
        mRecyclerView.addHeaderView(defineHeadView);
        View iv_search = inflate.findViewById(R.id.iv_search);
        View brand = inflate.findViewById(R.id.brand);

        TextView tv_more_limit = defineHeadView.findViewById(R.id.tv_more_limit);
        TextView tv_more_new = defineHeadView.findViewById(R.id.tv_more_new);
        TextView tv_more_buy = defineHeadView.findViewById(R.id.tv_more_buy);

        tv_more_limit.setOnClickListener(this);
        tv_more_new.setOnClickListener(this);
        tv_more_buy.setOnClickListener(this);

        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.addItemDecoration(new StaggeredDividerItemDecoration(mContext, (int) getResources().getDimension(R.dimen.dp_11)));
        mRecyclerView.loadMoreFinish(false, false);

        mSmartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mSmartRefreshLayout.setEnableLoadMore(true);
                pageIndex = 1;
                getActivityData();
                getAllProductData();
            }

            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                pageIndex++;
                getAllProductData();
            }

        });
        mSmartRefreshLayout.autoRefresh();

        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), SearchActivity.class));
            }
        });
        brand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), BrandActivity.class));
            }
        });
    }

    NoDataView noDataView;
    private void setNUllDataView(boolean isNUllData) {
        ll_content = inflate.findViewById(R.id.ll_content);
       if(noDataView == null){
           noDataView = new NoDataView(getContext());
       }else {//不为空说明添加过
           root_view.removeView(noDataView);
        }

        if(isNUllData){
            root_view = inflate.findViewById(R.id.root_view);
            ll_content.setVisibility(View.GONE);

                root_view.addView(noDataView);
                noDataView.setVisibility(View.VISIBLE);


        }else{
            noDataView.setVisibility(View.GONE);
            ll_content.setVisibility(View.VISIBLE);
        }


        noDataView.setClick(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                initData();
            }
        });
    }

    /*
    * tv_more_limit
tv_more_new
tv_more_buy
    * */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_more_limit:
                //加载更多
                Intent intent = new Intent(mContext,ActionActivity.class);
                intent.putExtra("type", ActionActivity.type_limit);
                startActivity(intent);
                break;
            case R.id.tv_more_new:
                Intent intent1 = new Intent(mContext,ActionActivity.class);
                intent1.putExtra("type", ActionActivity.type_new);
                startActivity(intent1);
                break;
            case R.id.tv_more_buy:
                Intent intent2 = new Intent(mContext,ActionActivity.class);
                intent2.putExtra("type", ActionActivity.type_buy);
                startActivity(intent2);
                break;
        }
    }

    public class HomeNewAdapter extends RecyclerView.Adapter<HomeNewAdapter.ViewHolder>{
        private List<PageAllProductBean.DataBean.RecordsBean> mDataList;

        public HomeNewAdapter( List<PageAllProductBean.DataBean.RecordsBean>  records){
            mDataList = records;
        }
        public void setData(List<PageAllProductBean.DataBean.RecordsBean> records) {
            mDataList = records;
            notifyDataSetChanged();
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_new_item, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new HomeNewAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            if(position % 2 == 0){
                holder.left_View.setVisibility(View.VISIBLE);
                holder.right_View.setVisibility(View.GONE);
            }else{
                holder.left_View.setVisibility(View.GONE);
                holder.right_View.setVisibility(View.VISIBLE);
            }
            try {
                PageAllProductBean.DataBean.RecordsBean recordsBean = mDataList.get(position);

                holder.name.setText(recordsBean.getProductName());
                holder.price.setText("¥"+recordsBean.getProductPrice() + "");
                Glide.with(holder.picture.getContext()).load(recordsBean.getAbbreviationPic()).into(holder.picture);

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(mContext, ProductNewActivity.class);
                        Log.e("@@@@@",""+recordsBean.getProductId());
                        intent.putExtra("id",recordsBean.getProductId());
                        intent.putExtra("brandId",recordsBean.getBrandId() + 0L);
                        mContext.startActivity(intent);

                    }
                });
            }catch (Exception e){

            }
        }

        @Override
        public int getItemCount() {
            if(mDataList == null){
                return 0;
            }
            return mDataList.size();
        }



        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView name;
            TextView price;
            ImageView picture;
            View left_View;
            View right_View;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.name);
                price = itemView.findViewById(R.id.price);
                picture = itemView.findViewById(R.id.picture);
                left_View = itemView.findViewById(R.id.left_View);
                right_View = itemView.findViewById(R.id.right_View);
            }
        }
    }

    @Override
    public void onLazyLoad() {
    }

    private void initData() {
        homeNewAdapter = new HomeNewAdapter(null);
        mRecyclerView.setAdapter(homeNewAdapter);

       getActivityData();
       getAllProductData();
    }

    private void getAllProductData() {
        String url = DataManager.BaseUrl_weicheng + "mall/shopproductinfo/pageAllProduct?current=" + pageIndex + "&size=" + pageSize;

        /**
         * 去除tokenjjm
         */
//        HashMap<String, String> headMap = new HashMap<>();
//        headMap.put("HavT", "NoToken");

        DataManager.toServer3(getContext(), url, DataManager.GET_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                mSmartRefreshLayout.finishRefresh();
                mSmartRefreshLayout.finishLoadMore();
                try {
                    PageAllProductBean productBean = JSON.parseObject(response, PageAllProductBean.class);
                    List<PageAllProductBean.DataBean.RecordsBean> records = productBean.getData().getRecords();
                    Log.e("@@",""+records.get(1).getProductId());
                    if (records == null) {
                        return;
                    }

                    if (1 == pageIndex) {
                        recordDatas.clear();
                        recordDatas.addAll(records);
                    } else {
                        recordDatas.addAll(records);
                    }

                    if (homeNewAdapter != null) {
                        homeNewAdapter.setData(recordDatas);
                        homeNewAdapter.notifyDataSetChanged();
                    }

                    if (records.size() < pageSize) {
                        mSmartRefreshLayout.setEnableLoadMore(false);
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    //获取活动数据
    private void getActivityData() {
        String url = DataManager.BaseUrl_weicheng + "mall/shopproductinfo/page?current=1&size=1000";

        /**
         * 去除tokenjjm
         */
//        HashMap<String, String> headMap = new HashMap<>();
//        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(getContext()));

        DataManager.toServer3(getContext(), url, DataManager.GET_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    ShopProductInfoBean shopProductInfoBean = JSON.parseObject(response, ShopProductInfoBean.class);
                    if(shopProductInfoBean.getCode() != 0){
                        //todo 暂时去除空界面显示
//                        setNUllDataView(true);
                    }
                    List<ShopProductInfoBean.DataBean> data = shopProductInfoBean.getData();
                    System.out.println();
                    if(data == null)
                        return;
                    detailActivity(data);
                }catch (Exception e){
                    //todo 暂时去除空界面显示
//                    setNUllDataView(true);
                }
            }
        });
    }

    //处理活动数据
    private void detailActivity(List<ShopProductInfoBean.DataBean> data) {
        try {
            for (int i = 0; i < data.size(); i++) {
                ShopProductInfoBean.DataBean dataBean = data.get(i);
                String activityCode = dataBean.getActivityCode();
                if(TextUtils.isEmpty(activityCode)){
                    continue;
                }

                switch (activityCode){
                    case "time_limit_activities"://限时特价
                        List<ShopProductInfoBean.DataBean.NewObjBean> limit_newObj = dataBean.getNewObj();
                        if(limit_newObj != null){
                            defineHeadView.setLimitData(limit_newObj);
                            defineHeadView.setLimitISVisble(true);
                        }else{
                            defineHeadView.setLimitISVisble(false);
                        }
                        break;

                    case "discount_activities"://折扣券活动-新品来袭
                        List<ShopProductInfoBean.DataBean.NewObjBean> discount_newObj = dataBean.getNewObj();
                        if(discount_newObj != null){
                            defineHeadView.setNewData(discount_newObj);
                            defineHeadView.setNewISVisble(true);
                        }else{
                            defineHeadView.setNewISVisble(false);
                        }
                        break;

                    case "hand_speed_activities"://满减活动-买家推荐
                        List<ShopProductInfoBean.DataBean.NewObjBean> reduce_newObj = dataBean.getNewObj();
                        TextView tv_desc = defineHeadView.findViewById(R.id.tv_buy_tuijian_desc);
                        tv_desc.setVisibility(View.GONE);
                        if(reduce_newObj != null){
                            defineHeadView.setMaiData(reduce_newObj);
                            defineHeadView.setMaiISVisble(true);
                            TextView tv_title = defineHeadView.findViewById(R.id.tv_buy_tuijian);
                            tv_title.setText(dataBean.getActName());
                        }else{
                            defineHeadView.setMaiISVisble(false);
                        }

                        break;

                }

                if(homeNewAdapter != null){
                    homeNewAdapter.notifyDataSetChanged();
                }
            }
        }catch (Exception e){
        }
    }

    HomeNewAdapter homeNewAdapter;
}
